import React, { useEffect, useState, useRef, useContext, useCallback } from 'react';
import placeholderImage from '../assets/img/C.png';
import consultantStatus from '../assets/img/1.png';
import { connect } from 'react-redux';
import Countdown from './Countdown';
import image9 from '../assets/img/9.png';
import AudioContext from '../AudioContext';
import enteringVideo from '../assets/img/A.mp4';
import conversingVideo from '../assets/img/B.mp4';

// 添加音量检测函数
function getVolume(analyser) {
    if (!window._audioContextAnalyserDataArray) {
        window._audioContextAnalyserDataArray = new Uint8Array(analyser.frequencyBinCount);
    }
    const analyserDataArray = window._audioContextAnalyserDataArray;

    analyser.getByteTimeDomainData(analyserDataArray);

    let sum = 0;
    for (let i = 0; i < analyserDataArray.length; i++) {
        sum += Math.abs(analyserDataArray[i] - 128);
    }

    const average = sum / analyserDataArray.length;
    return average / 128;
}

const RoomMain = ({ isOnline, countdownStarted, countdownTime }) => {
    const { analyser } = useContext(AudioContext);
    const enteringVideoRef = useRef(null);
    const conversingVideoRef = useRef(null);
    const [statusZIndex, setStatusZIndex] = useState({
        idle: 0,
        entering: 0,
        conversing: 0,
    });
    const [imageSrc, setImageSrc] = useState(placeholderImage);
    const [imageStyle, setImageStyle] = useState({});
    const [isMaster, setIsMaster] = useState(false);

    useEffect(() => {
        const queryParams = new URLSearchParams(window.location.search);
        const master = queryParams.get('master') === '1';
        setIsMaster(master);

        if (master) {
            setImageSrc(image9);
            setImageStyle({ width: '260px', height: '260px' });
        }
    }, []);

    const changeStatus = useCallback(status => {
        const newStatusZIndex = {
            idle: 0,
            entering: 0,
            conversing: 0,
        };
        newStatusZIndex[status] = 1;
        setStatusZIndex((pre) => {
            if (status === 'entering') {
                enteringVideoRef.current.currentTime = 0;
                enteringVideoRef.current.play();
            } else if (status === 'conversing') {
                if (pre.conversing === 0) {
                    conversingVideoRef.current.currentTime = 0;
                }
            }
            return newStatusZIndex;
        });
    }, []);

    useEffect(() => {
        if (isOnline) {
            changeStatus('entering');
        } else {
            changeStatus('idle');
        }
    }, [isOnline, changeStatus]);

    useEffect(() => {
        let idleCount = 0;
        const timer = setInterval(() => {
            const volume = getVolume(analyser);
            if (volume > 0.05) {
                changeStatus('conversing');
                idleCount = 0;
            } else {
                idleCount++;
                if (idleCount > 10) {
                    changeStatus('idle');
                    idleCount = 0;
                }
            }
        }, 100);
        return () => clearInterval(timer);
    }, [analyser, changeStatus]);

    return (
        <div className="room-main" style={{ backgroundColor: !isMaster ? '#F4EADE' : 'white' }}>
            <div className="room-container">
                {countdownStarted && (
                    <Countdown initialTime={countdownTime} onComplete={() => console.log('Countdown complete')} />
                )}

                {/* 视频网格区域 */}
                <div className="participants-grid" style={{ height: !isMaster ? '375px' : '320px'}}>
                    <div className="video-placeholder" style={{ height: !isMaster ? '375px' : '320px', alignItems: !isMaster ? 'center' : 'flex-end' }}>
                        <img src={imageSrc} alt="Video placeholder" style={imageStyle} />
                    </div>
                    <div className="video-placeholder video-content" style={{ zIndex: statusZIndex.entering }}>
                        <video ref={enteringVideoRef} src={enteringVideo} controls={false} />
                    </div>
                    <div className="video-placeholder video-content" style={{ zIndex: statusZIndex.conversing }}>
                        <video ref={conversingVideoRef} src={conversingVideo} autoPlay loop controls={false} />
                    </div>
                    <div className="video-placeholder video-content" style={{ zIndex: statusZIndex.idle }}>
                        <video src={enteringVideo} controls={false} />
                    </div>
                </div>

                {/* 咨询师状态列表 */}
                <div className="consultant-status-list" style={{ marginTop: !isMaster ? '0' : '20px', marginBottom: !isMaster ? '0' : '100px' }}>
                    {!isMaster && (
                        <img src={consultantStatus} alt="Video placeholder" />
                    )}
                    <span className={`status-text ${isOnline ? 'online' : 'offline'}`}>
                        {isOnline ? '语音聊天中...' : '等等我，马上上线'}
                    </span>
                </div>
                {/* 风险提示 */}
                <p className="risk-tip">您的身份已加密，声音已变音，<br/>{!isMaster ? '倾听者' : '双方'}和平台均不知道您的身份，请放心聊天</p>
            </div>
        </div>
    );
};

const mapStateToProps = (state) => {
    return {
        isOnline: state.peers && Object.keys(state.peers).length > 0
    };
};

export default connect(mapStateToProps)(RoomMain); 
